<?php

namespace App\Http\Controllers\LibApi;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 * 图书馆api接口  本地测试
 */
class LibApiController
{


    private static $appId = 'beitu_yblib'; //测试环境
    private static $appSecret = 'jndhxkkpm7g80onb47rpbixd4ayw8zn4'; //测试环境

    // private static $appId = 'beitu'; //正式环境  与测试环境一致
    // private static $appSecret = 'hyfru654st4sdgwfgrg47a122tj8dgez'; //正式环境



    private static $serviceAddr = 'http://125.70.14.137:9002'; //本地测试服务器地址     2023.5.18更换
    // private static $serviceAddrOpac = 'http://opac.sclib.org:8088'; //本地测试服务器地址   2023.5.18更换
    private static $serviceAddrOpac = 'http://opac.sclib.cn:8088'; //本地测试服务器地址   2025.2.13更换
    // private static $serviceAddr = 'http://125.80.96.7:19007'; //正式服务器外网地址
    // private static $serviceAddr = '';//正式服务器内网地址


    private static $adminName = 'YBBTKJ'; //测试地址  操作管理员账号
    private static $password = 'YB@2024'; //测试地址  操作管理员密码


    private static $getToken = '/openlib/service/barcode/token'; //获取token（指定地址）
    private static $login = '/openlib/service/reader/confirmreader'; //获取token（指定地址）
    private static $searchreaderlist = '/openlib/service/reader/searchreaderlist'; //多条件查询读者列表（群）

    private static $getNowBorrow = '/openlib/service/barcode/rdloanlist'; //查询读者当前借阅（群）(校验借书接口-需授权)
    private static $getHistoryBorrow = '/openlib/service/barcode/historyloan'; //查询读者历史借阅

    private static $validateBorrow = '/openlib/service/reader/loanreader'; //借阅前查询读者(群)
    private static $renew = '/openlib/service/barcode/renewbook'; //续借（群）


    private static $borrow = '/openlib/service/barcode/loanbook'; //借书（群）
    private static $canBorrowNumber = '/openlib/service/reader/canloannum'; //查询可借数
    private static $returnBook = '/openlib/service/barcode/returnbook'; //还书（群）
    private static $readerIdAdd = '/openlib/service/reader/addreader'; //新增读者


    private static $getReaderType = '/openlib/service/statis/sync/74'; //查询读者类型
    private static $getLibCode = '/openlib/service/statis/sync/42'; //查询所有分馆代码


    private static $getBookInfo = '/opac/advance/search'; //检索接口
    private static $getBookDetail = '/opac/api/book'; //书目记录号获取书目信息接口

    private static $getAssetByBarcode = '/openlib/service/hold/queryholdings'; //根据条形码获取书籍信息

    private static $getLibBaseInfo = '/opac/api/holding/0'; //文献类型和分馆列表

    private static $cardManage = '/openlib/service/reader/cardmanage'; //读者证管理
    private static $editReader = '/openlib/service/reader/editreader'; //修改读者


    /**
     * 获取  access_token （已对接）
     * http://125.70.14.137:9002/openlib/service/barcode/token?appid=beitu_yblib&secret=jndhxkkpm7g80onb47rpbixd4ayw8zn4
     */
    public function getAccessToken()
    {
        $url = self::$serviceAddr . self::$getToken;

        $access_token_param = "appid=" . self::$appId . '&secret=' . self::$appSecret;

        $result = $this->RequestCurl($url . '?' . $access_token_param); //必须post请求，但是参数需要像get那样拼接
        $results = json_decode($result, true); //json字符串转为数组
        if (empty($results) || $results['success'] !== true) {
            Log::error($results); //记录失败信息
            exit(json_encode(['code' => 202, 'msg' => 'access_token获取失败']));
        }

        $access_token = $results['messagelist'][0]['token'];
        $expires_in = strtotime($results['messagelist'][0]['time']) - time();

        //储存access_token
        Cache::put("scyblib_access_token", $access_token, $expires_in); //缓存3600秒

        return $access_token;
    }

    /**
     * 登录接口   （已对接） 读者证号登录
     *
     * 测试读者证号：宜宾市图书馆测试读者账号 51150110004020 密码 123456
     * @param $account  读者证号
     * @param $password   密码
     */
    public function login($account, $password)
    {
        $user_info = [];

        //只认读者证号，不认身份证号码
        // if (is_legal_no($account)) {
        //     //判断是否是身份证号登录
        //     $user_info = $this->idCardlogin($account);
        //     if ($user_info['code'] !== 200) {
        //         return ['code' => 202, 'msg' => $user_info['msg']];
        //     }
        //     $account = $user_info['content'][0]['account'];
        // }

        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$login;

        $param = 'token=' . $access_token . '&rdid=' . $account . '&rdpasswd=' . $password . '&localvalid=1&havecluster=&globalid=&includeTmpReader=&opuser=' . self::$adminName;
        $result = $this->RequestCurl($url . '?' . $param);
        $results = json_decode($result, true); //json字符串转为数组
        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token =  $this->getAccessToken();
            $param = 'token=' . $access_token . '&rdid=' . $account . '&rdpasswd=' . $password . '&localvalid=1&havecluster=&globalid=&includeTmpReader=&opuser=' . self::$adminName;
            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url . '?' . $param);
        //写入错误日志
        Log::channel('libapi')->info($results);

        if ($results['success'] === true) {
            if (empty($user_info)) {
                $user_info = $this->searchreaderlist($account, 'rdid');
                if ($user_info['code'] !== 200) {
                    return ['code' => 202, 'msg' => $user_info['msg']];
                }
            }
            return ['code' => 200, 'msg' => '登录成功', 'content' => !empty($user_info['content'][0]) ? $user_info['content'][0] : $user_info['content']];
            // if ($results['objectData']['status'] == 'n') {
            //     return ['code' => 200, 'msg' => '登录成功', 'content' => $results['objectData']];
            // } elseif ($results['objectData']['status'] == 'l') {
            //     $msg = '登录失败，该读者证挂失中';
            // } elseif ($results['objectData']['status'] == 'd') {
            //     $msg = '登录失败，该读者证已注销';
            // } else {
            //     $msg = '登录失败，该读者证状态异常';
            // }
            // return ['code' => 202, 'msg' => $msg];
        }
        return ['code' => 202, 'msg' => '读者证号或密码不正确'];
    }

    /**
     * 登录接口（已对接）身份证号登录 (不能直接登录，只能获取读者号码，然后在根据读者证号进行登录)
     * @param $account  读者证号
     * @param $password   密码
     */
    public function idCardlogin($id_card)
    {
        $account_info = $this->searchreaderlist($id_card, 'rdcertify');
        if ($account_info['code'] == 200) {
            if (count($account_info['content']) != 1) {
                return ['code' => 202, 'msg' => '当前身份证号码对应多个读者证号，请使用读者证号进行绑定'];
            }
            return ['code' => 200, 'msg' => '获取成功', 'content' => $account_info['content']];
        }
        return ['code' => 202, 'msg' => '获取用户信息失败'];
    }




    /**
     * 多条件查询读者列表（群）
     * @param keywords_type  查询类型 rdid 读者证号 rdname读者姓名 rdcertify身份证号 othercardno其他编号 workcardno工作/学生证号 rdphone电话 rdloginid手机 cardid附属卡(IC卡)
     * @param keywords   检索值
     * @param havecluster   是否查集群读者 1 是，0否
     *
     *
     * @return  返回状态 有效=1、验证=2、丢失=3、暂停=4、注销=5
     * @param  $status 需要的读者证号状态
     */
    public function searchreaderlist($keywords, $keywords_type = 'rdid', $status = [])
    {
        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$searchreaderlist;

        $param = 'token=' . $access_token . '&selecttype=' . $keywords_type . '&queryvalue=' . $keywords;
        $result = $this->RequestCurl($url . '?' . $param);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token =  $this->getAccessToken();
            $param = 'token=' . $access_token . '&selecttype=' . $keywords_type . '&queryvalue=' . $keywords;
            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url . '?' . $param);
        //写入错误日志
        Log::channel('libapi')->info($results);

        if ($results['success'] === true) {
            $lib_base_info = $this->getLibBaseInfo();
            // $lib_base_info = $this->getReaderType('QDNZTSG');
            // dump($lib_base_info);die;
            $data = [];
            $i = 0;
            foreach ($results['pagedata'] as $key => $val) {
                $val['lib_name'] = !empty($lib_base_info['libcodeMap'][$val['rdlib']]) ? $lib_base_info['libcodeMap'][$val['rdlib']] : config('other.lib_name');
                $val['libid'] = $val['rdlib'];
                $val['account'] = $val['rdid'];
                $val['sex'] = $val['rdsex'] == '男' ? 1 : 2; //1男 2女
                $val['id_card'] = !empty($val['rdcertify']) ? $val['rdcertify'] : null;
                $val['username'] = $val['rdname'];
                $val['status'] = $val['rdcfstate'];
                $val['status_name'] = $this->getReaderStatus($val['rdcfstate']);
                $val['address'] = null;
                $val['tel'] = $val['rdphone'];
                $val['start_time'] = $val['rdstartdate'];
                $val['end_time'] = $val['rdenddate'];
                $val['register_time'] = $val['rdstartdate'];
                $val['type'] = $val['rdtype'];
                $val['email'] = $val['rdemail'];
                if ($keywords_type == 'rdcertify') {
                    $val['id_card'] = $keywords;
                }
                if ($status) {
                    if (in_array($val['rdcfstate'], $status)) {
                        $data[$i] = $val;
                        $i++;
                    }
                    continue;
                } else {
                    $data[$i] = $val;
                    $i++;
                }
            }

            if ($keywords_type == 'rdid' && $data) {
                return ['code' => 200, 'msg' => '获取成功', 'content' => $data[0]]; //如果是读者证号登录，返回一维数组
            }
            return ['code' => 200, 'msg' => '获取成功', 'content' => $data]; //其他还是返回二维数组
        }
        return ['code' => 202, 'msg' => '读者信息获取失败'];
    }
    public function getReaderStatus($status)
    {
        switch ($status) {
            case 1:
                return '有效';
                break;
            case 2:
                return '验证';
                break;
            case 3:
                return '丢失';
                break;
            case 4:
                return '暂停';
                break;
            case 5:
                return '注销';
                break;

            default:
                return null;
        }
    }

    /**
     * 当前借阅记录   （已对接）
     * @param account 读者证号
     * @param page 页数
     * @param limit 读者证号
     * @param $ban_code 条形码
     * @return array
     */
    public function getNowBorrowList($account, $pageNum = 1, $pageSize = 10, $ban_code = null)
    {
        if ($pageNum != 1) return ['code' => 202, 'msg' => '暂无数据'];

        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }
        $url  = self::$serviceAddr . self::$getNowBorrow;

        $param = 'token=' . $access_token . '&rdid=' . $account;
        $result = $this->RequestCurl($url . '?' . $param);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token =  $this->getAccessToken();
            $param = 'token=' . $access_token . '&rdid=' . $account;
            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }
        if ($results['success'] !== true || empty($results['loanlist'])) {
            return ['code' => 202, 'msg' => '暂无数据'];
        }

        $data = [];
        $i = 0;
        //  dump($param);
        foreach ($results['loanlist'] as $key => $val) {
            if (!empty($ban_code)) {
                if ($val['barcode'] == $ban_code) {
                    $data[0]['book_name'] = $val['title'];
                    $data[0]['author'] = '';
                    $data[0]['book_num'] = $val['callno'];
                    $data[0]['price'] = $val['singleprice'];
                    $data[0]['barcode'] = $val['barcode'];

                    $data[0]['borrow_time'] = $val['loandate'];
                    $data[0]['expire_time'] = $val['returndate'];
                    $data[0]['ISBN'] = $val['isbn'];
                    $data[0]['press'] = '';
                    $data[0]['renew_num'] = $val['loancount'];
                    // $data[0]['callno'] = $val['callno'];//书目索取号
                    break;
                }
            } else {
                $data[$i]['book_name'] = $val['title'];
                $data[$i]['author'] = '';
                $data[$i]['book_num'] = $val['callno'];
                $data[$i]['price'] = $val['singleprice'];
                $data[$i]['barcode'] = $val['barcode'];

                $data[$i]['borrow_time'] = $val['loandate'];
                $data[$i]['expire_time'] = $val['returndate'];
                $data[$i]['ISBN'] = $val['isbn'];
                $data[$i]['press'] = '';
                $data[$i]['renew_num'] = $val['loancount'];
                $i++;
            }
        }
        if ($data) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $data];
        }
        return ['code' => 202, 'msg' => '暂无数据'];
    }

    /**
     * 查询读者历史借阅分页列表-根据读者证号 （已对接）
     * @param account 读者证号
     * @param pageNum 分页页码
     * @param pageSize 分页大小
     * @param year 借阅年份，不传默认为今年
     * @param startDate 借阅开始日期
     * @param endDate 借阅结束日期
     *
     * @param $logtype 借 30001 还 30002
     *
     * @return array
     *
    /** 读者借出Ea  */
    //BORROW("Ea", "读者借出"),
    /** 读者还回文献Eg */
    //  RETURN("Eg", "读者还回文献"),    //下面的枚举值，不能管什么情况，都会产生一条这个数据
    /** 读者续借Eb */
    // RENEW("Eb", "读者续借"),
    /** 读者过期Ec */
    //  OVERDUE("Ec", "读者过期"),
    /** 文献损坏Ed */
    //  DAMAGE("Ed", "文献损坏"),
    /** 读者丢失文献Ef */
    //  LOST("Ef", "读者丢失文献"),
    //logtype	否	借 30001 还 30002

    //token 每次要替换最新的
    //http://125.70.14.137:9002/openlib/service/barcode/historyloan?token=88e931b55b9bdeab98af58fd9019afef-38ad37d5d469c0288d1bf58cd0384a5d&rdid=51150110004020&logtype=30001

    public function getReturnData($account, $pageNum = 1, $pageSize = 100, $startDate = null, $endDate = null, $barcode = null, $logtype = '30002', $is_return_directly =  false)
    {

        if ($pageNum != 1) return ['code' => 202, 'msg' => '暂无数据'];

        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $startDate = !empty($startDate) ? $startDate : date("Y-m-d", strtotime("-3 year"));
        $endDate = !empty($endDate) ? $endDate : date("Y-m-d");

        $url  = self::$serviceAddr . self::$getHistoryBorrow;

        $param = 'token=' . $access_token . '&rdid=' . $account . '&startdate=' . $startDate . '&enddate=' . $endDate . '&page' . $pageNum . '&rows=' . $pageSize . '&logtype=' . $logtype;
        $result = $this->RequestCurl($url . '?' . $param);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token =  $this->getAccessToken();
            $param = 'token=' . $access_token . '&rdid=' . $account . '&startdate=' . $startDate . '&enddate=' . $endDate . '&page' . $pageNum . '&rows=' . $pageSize . '$logtype=' . $logtype;
            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }
        //直接返回数据
        if ($is_return_directly) {
            return $results;
        }
        if ($results['success'] !== true || empty($results['hloanlist']) || empty($results['total'])) {
            return ['code' => 202, 'msg' => '暂无数据'];
        }

        $data = [];
        $i = 0;
        foreach ($results['hloanlist'] as $key => $val) {
            if (!empty($barcode)) {
                if ($val['barcode'] == $barcode) {
                    $data[0]['book_name'] = $val['title'];
                    $data[0]['author'] = $val['author'];
                    $data[0]['book_num'] = '';
                    $data[0]['price'] = '';
                    $data[0]['barcode'] = $val['barcode'];

                    $data[0]['borrow_time'] = !empty($val['loantime']) ? $val['loantime'] : ''; //optime 发生时间（根据logtype 30001 借 30002 还 来判断）   returntime: 应还时间 loantime:借书时间
                    $data[0]['return_time'] = !empty($val['optime']) ? $val['optime'] : '';
                    $data[0]['ISBN'] = !empty($val['isbn']) ? $val['isbn'] : null;
                    $data[0]['press'] = '';
                    $data[0]['renew_num'] = $val['rownum_'];
                    // $data[0]['callno'] = $val['callno'];//书目索取号
                    break;
                }
            } else {
                $data[$i]['book_name'] = $val['title'];
                $data[$i]['author'] = $val['author'] ?? null;
                $data[$i]['book_num'] = '';
                $data[$i]['price'] = '';
                $data[$i]['barcode'] = $val['barcode'];

                $data[$i]['borrow_time'] = !empty($val['loantime']) ? $val['loantime'] : '';
                $data[$i]['return_time'] = !empty($val['optime']) ? substr($val['optime'], 0, 10) : '';
                $data[$i]['ISBN'] = !empty($val['isbn']) ? $val['isbn'] : null;
                $data[$i]['press'] = '';
                $data[$i]['renew_num'] = $val['rownum_'];
                $i++;
            }
        }
        if ($data) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $data];
        }
        return ['code' => 202, 'msg' => '暂无数据'];
    }

    /**
     * 书目-opac书目检索-检索结果分页列表   (已对接)
     * http://ip:port/opac/advance/search?q=微信 开发 实战&searchWay=title&scWay=dim&sortWay=score&sortOrder=desc&return_fmt=json&view=json&page=1&rows=10
     * return_fmt：必须，用于限定报格式，固定为json
     *
     *   view：必须，用于限定报格式，固定为json
     *   q：检索词，可选参数
     *   searchWay：检索途径参数
     *   scWay：指定检索匹配方式，如：scWay=prefixMatch表示前方一致，scWay=dim表示模糊检索，scWay=full表示精确检索
     *   sortWay:排序方式，指定按匹配度，出版日期等排序，默认按匹配度排序，参数值列表如下：
     *   score 匹配度
     *   pubdate_sort 出版日期
     *   subject_sort 主题词
     *   title_sort 题名
     *   author_sort 著者
     *   callno_sort 索书号
     *   pinyin_sort 题名拼音
     *   loannum_sort 借阅次数
     *   title200h 卷册号
     *   renewnum_sort 续借次数
     *   title200Weight 题名权重
     *   title200aWeight 正题名权重
     *   sortOrder：排序方式，sortOrder=desc为降序（默认），sortOrder=asc为升序
     *    page：页码，非必须，默认为1
     *    rows：每页显示行数，非必须，默认为10

     *   searchWay：检索途径（题名，著者等等），非必须
     *   传值	说明
     *   title		题名
     *   title200a	正题名
     *   isbn		ISBN
     *   author	著者
     *   subject	主题
     *   class		分类号
     *   ctrlno	控制号
     *   orderno	订购号
     *   publisher	出版社
     *   callno	索书号
     *   高级检索参数：
     *   q0：第一检索词，可选参数，对应检索途径参数searchWay0
     *   q1：第二检索词，可选参数，对应检索途径参数searchWay1
     *   q2：第三检索词，可选参数，对应检索途径参数searchWay2
     *
     *
     *  TODO 如果同时检索多个馆的数据，可以试试  多个逗号分隔，例如检索A和B馆 curlibcodeGT=A,B  (未测试) 传这个时，就不要 libcode 这个参数
     */
    public function getBookInfo($content, $keywords_type = "isbn", $scWay = 'dim', $sortOrder = "desc", $page = 1, $limit = 10)
    {
        if ($keywords_type == 'classno') {
            $keywords_type = 'class';
        } else if ($keywords_type == 'all') {
            $keywords_type = '';
        }
        // $access_token = Cache::get('scyblib_access_token');
        // if (empty($access_token)) {
        //     $access_token =  $this->getAccessToken();
        // }

        $url  = self::$serviceAddrOpac . self::$getBookInfo;

        //isbn必须是精确检索
        // if ($keywords_type == 'isbn') {
        //     $scWay = 'full';
        // }

        // $content = urlencode($content); //参数需要编码  tenant=YB  只检索宜宾馆的书（感觉无效）
        //$param = 'tenant=YB&q=' . $content . '&searchWay=' . $keywords_type . '&scWay=' . $scWay . '&sortWay=score&sortOrder=' . $sortOrder . '&return_fmt=json&view=json&page=' . $page . '&rows=' . $limit;

        $content = urlencode($content); //参数需要编码  libcode=YB  只检索宜宾馆的书   orglib=YB (限制文献所属馆)
        $param = 'libcode=YB&orglib=YB&q=' . $content . '&searchWay=' . $keywords_type . '&scWay=' . $scWay . '&sortWay=score&sortOrder=' . $sortOrder . '&return_fmt=json&view=json&page=' . $page . '&rows=' . $limit;

        // http://ip:port/opac/advance/search?q=微信 开发 实战&searchWay=title&scWay=dim&sortWay=score&sortOrder=desc&return_fmt=json&view=json&page=1&rows=10

        $result = $this->RequestCurl($url . '?' . $param);

        $results = json_decode($result, true); //json字符串转为数组
        // if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
        //     $access_token =  $this->getAccessToken();
        //     $result = $this->RequestCurl($url . '?' . $param);
        //     $results = json_decode($result, true); //json字符串转为数组
        // }

        if (empty($results['bookList'])) {
            return ['code' => 202, 'msg' => '暂无数据'];
        }
        $data = [];
        foreach ($results['bookList'] as $key => $val) {
            $data['data'][$key]['bookrecno'] = $val['bookrecno'];
            $data['data'][$key]['metaid'] = $val['bookrecno']; //兼容其他项目
            $data['data'][$key]['book_name'] = $val['title'];
            $data['data'][$key]['author'] = isset($val['author']) ? $val['author'] : null;
            $data['data'][$key]['callno'] = isset($val['classno']) ? $val['classno'] : null; //索书号
            $data['data'][$key]['price'] = isset($val['price']) ? $val['price'] : null;

            $data['data'][$key]['ISBN'] = isset($val['isbn']) ? $val['isbn'] : null;

            $data['data'][$key]['img'] = '/default/default_lib_book.png';


            $data['data'][$key]['press'] = $val['publisher'];
            $data['data'][$key]['pre_time'] = $val['pubdate'];
            $data['data'][$key]['intro'] = $val['subject'];
        }
        $data['total'] = $results['totalCount'];
        $data['current_page'] = $results['page'];
        $data['per_page'] = $results['rows'];
        $data['last_page'] = null;
        return ['code' => 200, 'msg' => '获取成功', 'content' => $data];
    }

    /**
     * 书目记录号获取书目信息接口
     * bookrecno		书目记录号
     * http://118.122.168.64:8884/opac/api/book/261077
     */
    public function getBookDetail($bookrecno)
    {
        // $access_token = Cache::get('scyblib_access_token');
        // if (empty($access_token)) {
        //     $access_token =  $this->getAccessToken();
        // }

        $url  = self::$serviceAddrOpac . self::$getBookDetail;

        $param = $bookrecno;

        // http://ip:port/opac/advance/search?q=微信 开发 实战&searchWay=title&scWay=dim&sortWay=score&sortOrder=desc&return_fmt=json&view=json&page=1&rows=10

        $result = $this->RequestCurl($url . '/' . $param);
        $results = json_decode($result, true); //json字符串转为数组
        // if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
        //     $access_token =  $this->getAccessToken();
        //     $result = $this->RequestCurl($url . '?' . $param);
        //     $results = json_decode($result, true); //json字符串转为数组
        // }

        //  if (empty($results['biblios']) || empty($results['holdings'])) {
        if (empty($results['biblios'])) {
            return ['code' => 203, 'msg' => '馆藏数据查询失败'];
        }
        $data['bookrecno'] = $results['biblios']['bookrecno'];
        $data['book_name'] = $results['biblios']['title'];
        $data['author'] = $results['biblios']['author'];
        $data['book_num'] = $results['biblios']['classNo'];  //返回了 classno （分类号） 和 callno（索书号）
        $data['classno'] = $results['biblios']['classNo'];  //返回了 classno （分类号） 和 callno（索书号）
        $data['price'] = $results['biblios']['price'];
        $data['page'] = $results['biblios']['page'];
        $data['intro'] = $results['biblios']['subject'];

        $data['isbn'] = $results['biblios']['isbn'];
        $data['press'] = $results['biblios']['publisher'];
        $data['pre_time'] = $results['biblios']['pubdate'];

        $lib_base_info = $this->getLibBaseInfo();

        $data['holdings'] = [];
        $i = 0;
        foreach ($results['holdings'] as $key => $val) {
            if ($val['orglib'] != 'YB') {
                continue; //只显示宜宾市的书，不显示分馆的书
            }
            $data['holdings'][$i]['status'] = $val['state']; //馆藏状态，编目=1,在馆=2,借出=3,丢失=4,剔除=5,交换=6,赠送=7,装订=8,锁定=9,预借=10， 清点=12
            $data['holdings'][$i]['barcode'] = $val['barcode'];
            $data['holdings'][$i]['book_num'] = !empty($val['callno']) ? $val['callno'] : $results['biblios']['classNo'];//索书号
            $data['holdings'][$i]['initSublib'] = $val['orglib'];
            $data['holdings'][$i]['initLocal'] = $val['orglocal'];
            $data['holdings'][$i]['curSublib'] = $val['curlib'];
            $data['holdings'][$i]['curLocal'] = $val['curlocal'];
            $data['holdings'][$i]['cirtype'] = $val['cirtype'];
            $data['holdings'][$i]['initSublibNote'] = $lib_base_info['libcodeMap'][$val['orglib']];
            $data['holdings'][$i]['initLocalNote'] = $lib_base_info['localMap'][$val['orglocal']];
            $data['holdings'][$i]['curSublibNote'] = $lib_base_info['libcodeMap'][$val['curlib']];
            $data['holdings'][$i]['curLocalNote'] = $lib_base_info['localMap'][$val['curlocal']];
            $data['holdings'][$i]['cirtype_note'] = $lib_base_info['pBCtypeMap'][$val['cirtype']]['name'];
            $data['holdings'][$i]['regDate'] = $val['regdate'];
            $data['holdings'][$i]['shelfno'] = !empty($val['shelfno']) ? $val['shelfno'] : '';//架位号
            if (!$data['classno'] && !empty($val['callno'])) {
                //tang 如果书籍信息没分类信息，按条形码信息索书号来
                $data['classno'] = $val['callno'];
            }
            $i++;
        }

        return ['code' => 200, 'msg' => '获取成功', 'content' => $data];
    }


    /**
     * 文献类型和分馆列表通过这个接口获取
     * http://118.122.168.64:8884/opac/api/holding/0
     */
    public function getLibBaseInfo()
    {
        $lib_base_info = Cache::get("lib_base_info"); //缓存3600秒
        if (empty($lib_base_info)) {
            $url  = self::$serviceAddrOpac . self::$getLibBaseInfo;

            $result = $this->RequestCurl($url);
            $lib_base_info = json_decode($result, true); //json字符串转为数组
            Cache::set("lib_base_info", $lib_base_info, 60 * 60 * 7);
        }
        return $lib_base_info;
    }




    /**
     * 校验读者借书权限接口（借阅前查询读者(群)）
     * @param $account  读者证号
     * @param $barcode  馆藏条码号    新书  测试环境固定：01079300000147  渝中解放碑重庆书城
     * @param $barcode  馆藏条码号    新书  测试环境固定：01079300000153  渝中大坪重庆购书中心
     * @param $barcode  馆藏条码号    新书  正式环境固定：01039299999999  渝中解放碑重庆书城
     * @param $barcode  馆藏条码号    新书  正式环境固定：01039199999999  渝中大坪重庆购书中心
     * @return array
     * @param 01079300000147   01079300000153
     *
     *  private static $cqscAdminName = 'cqsc_bxdd_yz';//正式地址  操作管理员账号 渝中解放碑重庆书城
        private static $cqscPassword = '1234qwer';//正式地址  操作管理员密码

        private static $gszxAdminName = 'gszx_bxdd_yz';//正式地址  操作管理员账号 渝中大坪重庆购书中心
        private static $gszxPassword = '1234qwer';//正式地址  操作管理员密码
     */
    public function validateBorrow($account)
    {
        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$validateBorrow;

        $param = 'token=' . $access_token . '&rdid=' . $account . '&opuser=' . self::$adminName;
        $result = $this->RequestCurl($url . '?' . $param);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token =  $this->getAccessToken();
            $param = 'token=' . $access_token . '&rdid=' . $account . '&opuser=' . self::$adminName;
            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url . '?' . $param);
        //写入错误日志
        Log::channel('libapi')->info($results);

        if ($results['success'] === true && $results['right'] === true) {
            //是否开通馆际互借
            // if ($results['messagelist'][0]['code'] == 'R00027' || $results['messagelist'][0]['message'] == '未开通馆际借书！') {
            //     $results['readerinfo']['cloud_status'] = false; //没开通馆际互借
            // } else {
            //     $results['readerinfo']['cloud_status'] = true; //已开通馆际互借
            // }

            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['readerinfo']]; //返回读者信息
        }
        return ['code' => 202, 'msg' => '无借阅权限'];
    }



    /**
     * 查询可借数
     * @param  account 读者证号
     * @param  cirtype 文献流通类型
     * @param  local 所属馆藏地点
     */
    public function canBorrowNumber($account, $cirtype, $local)
    {
        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$canBorrowNumber;

        $param = 'token=' . $access_token . '&rdid=' . $account . '&cirtype=' . $cirtype . '&local=' . $local . '&opuser=' . self::$adminName;
        $result = $this->RequestCurl($url . '?' . $param);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token =  $this->getAccessToken();
            $param = 'token=' . $access_token . '&rdid=' . $account . '&cirtype=' . $cirtype . '&local=' . $local . '&opuser=' . self::$adminName;
            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url . '?' . $param);
        //写入错误日志
        Log::channel('libapi')->info($results);

        if ($results['success'] === true) {
            //是否开通馆际互借
            if (!empty($results['canloannum'])) {
                $data['number'] = $results['canloannum'];
            } else {
                $data['number'] = 0;
            }

            return ['code' => 200, 'msg' => '获取成功', 'content' => $data]; //R00027 未开通馆际借书！
        }

        return ['code' => 202, 'msg' => $results['messagelist'][0]['message']];
    }



    /**
     *  2.13流通-借书接口-需授权
     * @param $account  读者证号
     * @param $barcode  馆藏条码号
     * @param $transid  事务id，一个读者连续借多本传同一个值
     * @return array
     */
    public function bookBorrow($account, $barcode, $transid = null)
    {
        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$borrow;

        $param = 'token=' . $access_token . '&rdid=' . $account . '&barcode=' . $barcode . '&attachmentloanflag=1&opuser=' . self::$adminName;
        $result = $this->RequestCurl($url . '?' . $param);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token =  $this->getAccessToken();
            $param = 'token=' . $access_token . '&rdid=' . $account . '&barcode=' . $barcode . '&attachmentloanflag=1&opuser=' . self::$adminName;
            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url . '?' . $param);
        //写入错误日志
        Log::channel('libapi')->info($results);

        if ($results['success'] === true) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results]; //R00027 未开通馆际借书！
        }

        return ['code' => 202, 'msg' => $results['messagelist'][0]['message']];
    }



    /**
     *  流通-归还接口-需授权
     * @param $barcode  馆藏条码号
     * @param $borrowDateTime  归还时间
     * @return array
     */
    public function bookReturn($barcode)
    {
        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$returnBook;

        $param = 'token=' . $access_token . '&barcode=' . $barcode . '&opuser=' . self::$adminName;
        $result = $this->RequestCurl($url . '?' . $param);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token =  $this->getAccessToken();
            $param = 'token=' . $access_token . '&barcode=' . $barcode . '&opuser=' . self::$adminName;
            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url . '?' . $param);
        //写入错误日志
        Log::channel('libapi')->info($results);

        if ($results['success'] === true) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results]; //R00027 未开通馆际借书！
        }

        return ['code' => 202, 'msg' => $results['messagelist'][0]['message']];
    }

    /**
     *  流通-续借-续借单条-需授权
     * @param $account  读者证号
     * @param $barcode  馆藏条码号  条码号 多个用|分隔
     * @return array
     */
    public function renewBook($account, $barcode)
    {

        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$renew;

        $param = 'token=' . $access_token . '&rdid=' . $account . '&barcode=' . $barcode . '&opuser=' . self::$adminName;
        $result = $this->RequestCurl($url . '?' . $param);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token =  $this->getAccessToken();
            $param = 'token=' . $access_token . '&rdid=' . $account . '&barcode=' . $barcode . '&opuser=' . self::$adminName;

            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url . '?' . $param);
        //写入错误日志
        Log::channel('libapi')->info($results);

        if ($results['success'] === true) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results]; //R00027 未开通馆际借书！
        }
        return ['code' => 202, 'msg' => $results['messagelist'][0]['message']];
    }


    /**
     * 新增读者
     * 请求地址：{openlib.home.url}/service/reader/addreader?token=token&其它参数
                V3.5.1.20200116之后版本增加nocompress、ischain参数备注：读者网上填基本信息，
                系统分配一个虚拟号。读者提交申请办证，图创的接口将基本信息写入到ITNERLIB系统中，
                虚拟的卡在ITNERLIB系统中处于暂停状态。等读者到馆内凭电子凭证（虚拟的号码），
                到ITNERLIB系统中做换实体证处理。

     * @param $rdid  读者证号
     * @param $rdname  姓名
     * @param $rdpasswd  rdpasswd
     * @param $rdcertify       身份证
     * @param $rdtype  读者类型      以上是必填    对应读者证类型数据的 ：READERTYPE
     *
     * @param $rdloginid  手机号码  以下是非必填
     * @param $rdemail  email
     * @param $rdborndate 出生日期 格式：yyyy-MM-dd
     * @param $rdsex  性别 1 男 0女 不填默认1
     * @param $rdaddress  住址
     * @param $rdpostcode  邮编
     * @param $rdphone  电话号码
     * @param $rdunit  单位
     * @param $rdsort1  专业
     * @param $rdsort2  职业
     * @param $rdsort3  职务
     * @param $rdsort4  职称
     * @param $rdsort5  文化
     * @param $rdremark  备注
     * @param $rdnation  民族
     * @param $rdnative  籍贯
     * @param $rdcfstate  读者状态1 有效2验证3 挂失4 暂停（不填默认）5 注销10信用有效（V3.0.9.17060110及后续版本增加）
     * @param $deposit  押金
     * @param $paytype  押金支付方式，押金有值的时候传入1 现金 2 IC卡 5 支付宝 6 微信支付 7 银行卡支付
     * @param $serialno  订单流水号
     * @param $cardid  附属卡卡号
     * @param $type  附属卡类型
     * @param $rdstartdate  启用时间 格式：yyyy-MM-dd（不传取当前时间）
     * @param $rdenddate  终止时间 格式：yyyy-MM-dd（不传取当前时间+读者类型有效天数）
     * @param $rdintime  办证时间 格式：yyyy-MM-dd （不传取当前时间）
     * @param $departmant  系别
     * @param $grade 年级
     * @param $baseimg64  读者照片（ base64编码的二进制图片数据 ）
     * @param $nocompress  传1表示读者图片不进行压缩
     * @param $ischain  是否开通区块链
     * @param $othercardno  其他编号
     * @param $workcardno  工作/学生证号
     * @param $classnum  班级
     *
     *
     */
    public function readerIdAdd($data = null)
    {
        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $street = !empty($data['street']) ? $data['street'] : '';
        $datas = [
            'rdid' =>  $data['reader_id'], //读者证号
            'rdname' =>  $data['username'], //读者姓名
            'rdpasswd' =>  !empty($data['password']) ? $data['password'] : substr($data['id_card'], 6, 8), //读者证密码
            'rdcertify' =>  $data['id_card'], //读者身份证号码
            'rdtype' =>  $data['card_type'], //读者证类型
            'rdloginid' =>  $data['tel'], //电话号码
            'rdemail' =>  $data['email'], //email
            'rdborndate' =>  date('Y-m-d', strtotime(substr($data['id_card'], 6, 8))),
            'rdsex' =>  $data['sex'] == 1 ? 1 : 0, //性别
            'rdaddress' =>  isset($data['province']) ? $data['province'] . $data['city'] . $data['district'] . $street . $data['address'] : '',
            'rdpostcode' =>  $data['zip'],
            'rdphone' =>  $data['phone'],
            'rdunit' =>  $data['workunit'],
            'rdsort1' =>  '',
            'rdsort2' =>  '',
            'rdsort3' =>  '',
            'rdsort4' =>  '',
            'rdsort5' =>  '',
            'rdremark' =>  '',
            'rdnation' =>  '',
            'rdnative' =>  '',
            'deposit' =>  '',
            'paytype' =>  '',
            'serialno' =>  '',
            'cardid' =>  '',
            'type' =>  '',
            'rdstartdate' =>  date('Y-m-d'),
            'rdenddate' =>  '',
            'rdintime' =>  '',
            'departmant' =>  '',
            'grade' =>  '',
            'baseimg64' =>  '',
            'nocompress' =>  '',
            'ischain' =>  '',
            'othercardno' =>  '',
            'workcardno' =>  '',
            'classnum' =>  ''
        ];

        //固定参数
        $datas['operator'] =  self::$adminName; //办证人员
        $datas['rdlib'] =  'YB'; //rdlib
        $datas['rdcfstate'] =  1; //读者状态，传 1 ，就可以直接使用

        $param = http_build_query($datas); //转换为url地址拼接形式
        $param .= '&token=' . $access_token;
        $url = self::$serviceAddr . self::$readerIdAdd;

        $result = $this->RequestCurl($url, $param);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token = $this->getAccessToken();
            $param = http_build_query($datas); //转换为url地址拼接形式
            $param .= '&token=' . $access_token;

            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url . '?' . $param);
        //写入错误日志
        Log::channel('libapi')->info($results);

        if ($results['success'] === true) {
            return ['code' => 200, 'msg' => $results['messagelist'][0]['message'], 'content' => $results['messagelist']]; //办证成功
        }
        return ['code' => 202, 'msg' => $results['messagelist'][0]['message']];
    }

    /**
     *  查询读者类型
     *  返回的押金，单位为元
     */
    public function getReaderType($libcode = null)
    {
        if (empty($libcode)) {
            $libcode = 'QDNZTSG'; //黔东南州图书馆
        }
        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$getReaderType;

        $param = 'token=' . $access_token . '&libcode=' . $libcode . '&opuser=' . self::$adminName;
        $result = $this->RequestCurl($url . '?' . $param);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token =  $this->getAccessToken();
            $param = 'token=' . $access_token . '&libcode=' . $libcode . '&opuser=' . self::$adminName;
            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url . '?' . $param);
        //写入错误日志
        Log::channel('libapi')->info($results);

        if ($results['success'] === true && !empty($results['resultlist'])) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['resultlist']];
        }
        return ['code' => 202, 'msg' => '查询失败'];
    }
    /**
     *  查询所有分馆代码
     */
    public function getLibCode()
    {
        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }

        $url = self::$serviceAddr . self::$getLibCode;

        $param = 'token=' . $access_token . '&opuser=' . self::$adminName;
        $result = $this->RequestCurl($url . '?' . $param);
        $results = json_decode($result, true); //json字符串转为数组

        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token =  $this->getAccessToken();
            $param = 'token=' . $access_token . '&opuser=' . self::$adminName;
            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }
        if ($results['success'] === true && !empty($results['resultlist'])) {
            return ['code' => 200, 'msg' => '获取成功', 'content' => $results['resultlist']];
        }
        return ['code' => 202, 'msg' => '查询失败'];
    }

    /**
     * 校验读者身份证号是否存在(校验是否存在非注销状态读者)-需授权
     *
     * 未提供此接口，自己判断
     * @param idno 身份证号码
     */
    public function validateIdnoIsExist($idno)
    {
        $res = $this->searchreaderlist($idno, 'rdcertify');
        if ($res['code'] == 200) {
            foreach ($res['content'] as $key => $val) {
                if ($val['rdcfstate'] != 5) {
                    return ['code' => 200, 'msg' => '此身份证已经办理过读者证，请勿重复办理']; //表示已办过证
                }
            }
        }
        return ['code' => 202, 'msg' => '此身份证未办理过读者证']; //表示未办过证
    }

    /**
     * 根据条形码，获取书籍信息
     * @param barcode  条形码
     * @param libcode  条码结构参数的分馆 (可以只查询本馆的书)
     */
    public function getAssetByBarcode($barcode, $status = '')
    {
        //特殊处理条形码
        // if (stripos($barcode, 'AAAMM-') === false && stripos($barcode, 'Z') === false) {
        //     $barcode = 'AAAMM-' . $barcode;
        // }

        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }
        $url  = self::$serviceAddr . self::$getAssetByBarcode;

        $param = 'token=' . $access_token . '&barcode=' . $barcode;
        $result = $this->RequestCurl($url . '?' . $param);
        $results = json_decode($result, true); //json字符串转为数组
        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token =  $this->getAccessToken();
            $param = 'token=' . $access_token . '&barcode=' . $barcode;
            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }
        if ($results['success'] !== true || empty($results['pagelist'])) {
            return ['code' => 202, 'msg' => '暂无数据'];
        }
        $data['bookrecno'] = $results['pagelist']['0']['biblios']['bookrecno'];
        $data['metaid'] = $results['pagelist']['0']['biblios']['bookrecno']; //兼容其他项目
        $data['book_name'] = $results['pagelist']['0']['biblios']['title'];
        $data['author'] = $results['pagelist']['0']['biblios']['author'];
        $data['book_num'] = '';
        $data['price'] = $results['pagelist']['0']['biblios']['price'];
        $data['isbn'] = !empty($results['pagelist']['0']['biblios']['isbn']) ? $results['pagelist']['0']['biblios']['isbn'] : null;
        $data['press'] = $results['pagelist']['0']['biblios']['publisher'];

        foreach ($results['pagelist']['0']['holdingList'] as $key => $val) {
            if ($val['barcode'] == $barcode) {
                $data['orglib'] = $val['orglib'];
                $data['curlibname'] = $val['curlibname'];
                $data['callno'] = $val['callno'];
                $data['curlocal'] = $val['curlocal'];
                $data['curlib'] = $val['curlib'];
                $data['orglocalname'] = $val['orglocalname'];
                $data['cirtypename'] = $val['cirtypename'];
                $data['curlocalname'] = $val['curlocalname'];
                $data['cirtype'] = $val['cirtype'];
                $data['orglocal'] = $val['orglocal'];
                $data['regdate'] = $val['regdate'];
                $data['indate'] = $val['indate'];
                $data['state'] = $val['state']; //馆藏状态，编目=1,在馆=2,借出=3,丢失=4,剔除=5,交换=6,赠送=7,装订=8,锁定=9,预借=10， 清点=12
                $data['orglibname'] = $val['orglibname'];
                $data['bookrecno'] = $val['bookrecno'];
                $data['barcode'] = $val['barcode'];

                $data['status'] =  $data['state'] == '2' ? '在馆' : ($data['state'] == '3' ? '借出' : '其他');

                //    dump($data);die;
                if (!empty($status) && $data['status'] != $status) {
                    $msg = '获取书籍信息失败';
                    if ($status == '在馆') {
                        if ($data['status'] == '3') {
                            $msg = '当前书籍馆藏状态为外借状态';
                        } else {
                            $msg = '当前书籍馆藏状态异常，请联系管理员处理';
                        }
                    }
                    return ['code' => 202, 'msg' => $msg];
                }
                break;
            }
        }
        return ['code' => 200, 'msg' => '获取成功', 'content' => $data];
    }

    /**
     * 修改读者
     * @param rdid  读者证号
     * @param rdpasswd  密码(至少6位)
     * @param data  需要修改的数据，参考文档字段
     */
    public function changeReader($rdid, $data = [])
    {
        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }
        $url  = self::$serviceAddr . self::$editReader;

        $param = 'token=' . $access_token . '&rdid=' . $rdid;
        foreach ($data as $key => $val) {
            $param .= '&' . $key . '=' . $val;
        }
        $result = $this->RequestCurl($url . '?' . $param);
        $results = json_decode($result, true); //json字符串转为数组
        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token =  $this->getAccessToken();
            $param = 'token=' . $access_token . '&rdid=' . $rdid;
            foreach ($data as $key => $val) {
                $param .= '&' . $key . '=' . $val;
            }
            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }


        Log::channel('libapi')->info('URL：' . $url . '?' . $param);
        //写入错误日志
        Log::channel('libapi')->info($results);

        if ($results['success'] !== true) {
            return ['code' => 202, 'msg' => '修改失败'];
        }
        return ['code' => 200, 'msg' => '修改成功'];
    }

    /**
     * 读者证管理
     * @param currdid  读者证号
     * @param rdstate  证操作类型 1 恢复,2 验证,3 挂失, 4 暂停,5 注销,6 退证, 7 补办,8 延期,9 换证
     * @param data  需要修改的数据，参考文档字段
     */
    public function manageReader($currdid, $rdstate)
    {
        $access_token = Cache::get('scyblib_access_token');
        if (empty($access_token)) {
            $access_token =  $this->getAccessToken();
        }
        $url  = self::$serviceAddr . self::$cardManage;


        $user_info = $this->searchreaderlist($currdid, 'rdid');
        if ($user_info['code'] !== 200) {
            return ['code' => 202, 'msg' => $user_info['msg']];
        }

        if ($rdstate == 8 && date('Y-m-d', strtotime('-3 month', strtotime($user_info['content']['end_time']))) > date('Y-m-d')) {
            return ['code' => 202, 'msg' => '读者证有效期只能在到期前3个月内，才能延期读者证'];
        }
        $end_time = date('Y-m-d', strtotime('+1 year', strtotime($user_info['content']['end_time'])));

        $param = 'token=' . $access_token . '&currdid=' . $currdid . '&rdstate=' . $rdstate . '&opuser=' . self::$adminName;
        if ($rdstate == 8) {
            $param .= '&rdendate=' . $end_time;
        }

        $result = $this->RequestCurl($url . '?' . $param);
        $results = json_decode($result, true); //json字符串转为数组
        if (isset($results['success']) && $results['success'] !== true && !empty($results['messagelist'][0]['code']) && $results['messagelist'][0]['code'] == 'R00066') {
            $access_token =  $this->getAccessToken();
            $param = 'token=' . $access_token . '&currdid=' . $currdid . '&rdstate=' . $rdstate . '&opuser=' . self::$adminName;
            if ($rdstate == 8) {
                $param .= '&rdendate=' . $end_time;
            }
            $result = $this->RequestCurl($url . '?' . $param);
            $results = json_decode($result, true); //json字符串转为数组
        }

        Log::channel('libapi')->info('URL：' . $url . '?' . $param);
        //写入错误日志
        Log::channel('libapi')->info($results);

        if ($results['success'] !== true) {
            return ['code' => 202, 'msg' => '暂无数据'];
        }

        $user_info = $this->searchreaderlist($currdid, 'rdid');
        if ($user_info['code'] !== 200) {
            return ['code' => 202, 'msg' => $user_info['msg']];
        }

        return ['code' => 200, 'msg' => $this->getReaderOperStatus($rdstate), 'content' => $user_info['content']];
    }


    /**
     * 读者证操作状态
     */
    public function getReaderOperStatus($status)
    {
        switch ($status) {
            case 1:
                return '恢复成功';
                break;
            case 2:
                return '验证成功';
                break;
            case 3:
                return '挂失成功';
                break;
            case 4:
                return '暂停成功';
                break;
            case 5:
                return '注销成功';
                break;
            case 6:
                return '退证成功';
                break;
            case 7:
                return '补办成功';
                break;
            case 8:
                return '延期成功';
                break;
            case 9:
                return '换证成功';
                break;
            default:
                return null;
        }
    }




    /**
     * @param $url
     * @param null $params
     * @param bool $json  json  格式数据    Content-Type  需要修改  成 application/json
     * @return mixed
     */
    private  static  function RequestCurl($url, $params = null, $json = false)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        if (!empty($params)) {
            if (is_array($params)) {
                //如果传的是数组，就要进行对参数进行 &拼接
                $params = http_build_query($params);
            }
            if ($json) {
                curl_setopt(
                    $ch,
                    CURLOPT_HTTPHEADER,
                    array(
                        'Content-Type: application/json',
                        'Content-Length: ' . strlen($params)
                    )
                );
            }
            // curl_setopt($ch, CURLOPT_POST, 1);
            // curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        }
        //都是用post格式
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

        $body = curl_exec($ch);
        // dump(curl_error($ch));
        curl_close($ch);
        return $body;
    }
}
